home *** CD-ROM | disk | FTP | other *** search
- Path: beta.nedernet.nl!usenet
- From: jos@and.nl (Jos A. Horsmeier)
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: 5 Apr 1996 08:04:57 GMT
- Organization: AND Operations Research B.V.
- Message-ID: <4k2k79$ka9@beta.nedernet.nl>
- References: <31624BC2.70D2@sooner.net>
- NNTP-Posting-Host: klepzeiker.and.nl
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=ISO-8859-1
- X-Newsreader: WinVN 0.99.5
-
- In article <31624BC2.70D2@sooner.net>, edwbush@sooner.net wrote:
-
- |I am trying to construct a C function that will recursively convert
- |a string such as "1234" into it's integer equivelant (1234).
-
- I suspect this to be a homework problem, but, on the other hand, I've
- seen replies suggesting the following too:
-
- - using malloc() to store a temporary buffer;
- - modifying the character string argument;
- - using the pow() function;
- - using a char buf[100] temporary buffer.
-
- Is it because it's Friday? ;-) Normally when it's Friday I turn completely
- silly (it's got something to do with the weekend; dunno ...) but I didn't
- expect you ladies and gentlemen to pick me as a role model ;-)
-
- How about the following simple observation:
-
- let S be a string s_0, s_1 ... s_n, then the integer value of this
- string happens to be: atoir(S)= 10*atoir(s_0, s_1, ... s_n-1)+s_n-'0'
- if n contains more than one character, otherwise the result is simply
- s_0-'0' if the string S contains one characters, otherwise the result
- is undefined ...
-
- Sprinkling in some C lingo, we get something like this:
-
- int atoir(char* S, int n) {
-
- if (n < 0) /* undefined result */
- return rand(); /* slightly silly ... */
- else if (n == 0) /* just one digit */
- return S[0]-'0';
- else /* plunge into recursion */
- return 10*atoir(S, n-1)+ S[n]-'0';
- }
-
- Here's the wrapper for the function above:
-
- int atoiwrap(char* S) {
-
- return atoi(S, strlen(S)-1);
- }
-
- If you ladies and gentlemen will excuse me now, then I'll turn back to
- my normal silly-Friday-mood ;-)
-
- kind regards,
-
- Jos aka jos@and.nl (slightly silly on the right side; 12 points)
- --
- Atnwgqkrl gy zit vgksr, ug qshiqwtzoeqs!
-
-